<?php
namespace app\components\pay;

use Yii;
use yii\base\Exception;

use app\components\Func;

use app\models\Order;
use app\models\OrderRefund;

//和包支付组件
class HebaoPay {

    const URL_HEBAO_PAYMENT = '/hebao/payment';//联动优势_下单请求
    const URL_HEBAO_PAYMENT_CONFIRM = '/hebao/paymentConfirm';//联动优势_云支付支付确认
    const URL_HEBAO_REFUND = '/hebao/refund';//联动优势_退款
    const URL_HEBAO_CORRECT = '/hebao/correct';//联动优势_冲正
    const URL_HEBAO_QUERY = '/hebao/query';//联动优势_订单查询
    protected $parentObj;// PaymentAccount支付号对象

    public function __construct($parentObj) {
        $this->parentObj = $parentObj;
    }


    /**
     * 联动优势_下单请求
     * @param $phone 手机号
     * @param $order 订单对象
     */
    public function payment($phone, $order) {
        $timestamp = time();

        //准备参数
        $post_arr = [
            'mTrace' => $order->id,                                       //业务流水,pos批次号+流水号,这里用 我们的order_id代替
            'reqDate' => date('Ymd', $timestamp),                         //8位日期年月日,如 20131010
            'reqTime' => date('His', $timestamp),                         //6位时分秒,如 132018
            'posId' => $order->device_no,                                 //终端编号,设备号,如 DEV10552
            'calling' => $phone,                                          //手机号, 如 13112345678
            'pMerId' => $this->parentObj->partner_id,                     //商户号pMerId，由联动优势分配
            'amount' => $order->total_fee - $order->discount_fee,         //应付金额，单位为分
        ];

        //java签名
        $post_json = json_encode($post_arr);
        $sign = Yii::$app->kelaileJava->sign($timestamp,$post_json);
        //拼装请求路径 联动优势_下单请求
        $app_id = Yii::$app->kelaileJava->appid;
        $url = Yii::$app->kelaileJava->host.self::URL_HEBAO_PAYMENT."?appid={$app_id}&timestamp={$timestamp}&sign={$sign}";

        //请求java接口
        $javaRes = Func::postData($url, $post_json, 90, array('Content-Type: application/json; charset=utf-8'));
        return json_decode($javaRes,true);
    }

    /**
     * 联动优势_云支付支付确认
     * @param $identifyCode 支付验证码
     * @param $payInfo 支付信息数组
     */
    public function paymentConfirm($identifyCode, $payInfo){
        $timestamp = time();

        //准备参数
        $post_arr = [
            'mTrace' => $payInfo['res']['mTrace'],                               //业务流水,pos批次号+流水号,这里用 我们的order_id代替
            'reqDate' => date('Ymd', $timestamp),               //8位日期年月日,如 20131010
            'reqTime' => date('His', $timestamp),               //6位时分秒,如 132018
            'posId' => $payInfo['res']['posId'],                //终端编号,设备号,如 DEV10552
            'calling' => $payInfo['res']['calling'],            //手机号, 如 13112345678
            'pMerId' => $this->parentObj->partner_id,              //商户号pMerId，由联动优势分配
            'orderId' => $payInfo['res']['orderId'],            //联动优势返回的orderId
            'identifyCode' => $identifyCode,                    //支付验证码
        ];

        //java签名
        $post_json = json_encode($post_arr);
        $sign = Yii::$app->kelaileJava->sign($timestamp,$post_json);
        //拼装请求路径 联动优势_云支付支付确认
        $app_id = Yii::$app->kelaileJava->appid;
        $url = Yii::$app->kelaileJava->host.self::URL_HEBAO_PAYMENT_CONFIRM."?appid={$app_id}&timestamp={$timestamp}&sign={$sign}";

        //请求java接口
        $javaRes = Func::postData($url, $post_json, 90, array('Content-Type: application/json; charset=utf-8'));
        return json_decode($javaRes,true);
    }

    /**联动优势_退款
     * @param $orderPay order_pay对象
     * @param $refund_fee 退款金额
     * @param $deviceNo 设备号
     */
    public function refund($orderPay, $refund_fee, $deviceNo) {
        $timestamp = time();
        //订单对象
        $order = Order::getInstance($orderPay->order_id);
        //生成退款号
        $refund_trade_no = Func::getcode(10);

        //准备参数
        $post_arr = [
            'mTrace' => $order->id,                         //业务流水,订单号
            'reqDate' => date('Ymd', $timestamp),           //8位日期年月日,如 20131010
            'reqTime' => date('His', $timestamp),           //6位时分秒,如 132018
            'posId' => $deviceNo,                           //终端编号,设备号,如 DEV10552
            'calling' => $orderPay->payer,                  //手机号, 如 13112345678
            'pMerId' => $orderPay->payee,                   //商户号pMerId，由联动优势分配
            'orgOrderId' => $orderPay->trade_id,               //联动优势返回的orderId
        ];

        //获取签名
        $post_json = json_encode($post_arr);
        $sign = Yii::$app->kelaileJava->sign($timestamp,$post_json);

        //拼装请求路径 联动优势_云支付支付确认
        $app_id = Yii::$app->kelaileJava->appid;
        $url = Yii::$app->kelaileJava->host.self::URL_HEBAO_REFUND."?appid={$app_id}&timestamp={$timestamp}&sign={$sign}";

        //请求java接口
        $javaRes = Func::postData($url, $post_json, 90, array('Content-Type: application/json; charset=utf-8'));
        if(empty($javaRes)) throw new \Exception('请求超时',2022027);//可能超时

        //退款失败,code不为0即为有问题
        $javaRes = json_decode($javaRes,true);
        if($javaRes['code']) throw new \Exception("和包支付提示:\n" . isset($javaRes['res']['original_msg']) ? $javaRes['res']['original_msg'] : $javaRes['msg'],2022028);
        
        return [
            'refund_trade_no' => $refund_trade_no,
            'refund_trade_id' => $javaRes['res']['orderId'],//第三方退款单号
        ];
    }

    /**
     * 联动优势_冲正
     * @param $payInfo 支付信息数组
     */
    public function correct($payInfo) {
        $timestamp = time();

        //准备参数
        $post_arr = [
            'mTrace' => $payInfo['res']['mTrace'],                               //业务流水,pos批次号+流水号,这里用 我们的order_id代替
            'reqDate' => date('Ymd', $timestamp),               //8位日期年月日,如 20131010
            'reqTime' => date('His', $timestamp),               //6位时分秒,如 132018
            'posId' => $payInfo['res']['posId'],                //终端编号,设备号,如 DEV10552
            'calling' => $payInfo['res']['calling'],            //手机号, 如 13112345678
            'pMerId' => $this->parentObj->partner_id,              //商户号pMerId，由联动优势分配
            'orgOrderId' => $payInfo['res']['orderId'],            //联动优势返回的orderId
        ];

        //java签名
        $post_json = json_encode($post_arr);
        $sign = Yii::$app->kelaileJava->sign($timestamp,$post_json);
        //拼装请求路径 联动优势_云支付支付确认
        $app_id = Yii::$app->kelaileJava->appid;
        $url = Yii::$app->kelaileJava->host.self::URL_HEBAO_CORRECT."?appid={$app_id}&timestamp={$timestamp}&sign={$sign}";

        //请求java接口
        $javaRes = Func::postData($url, $post_json, 90, array('Content-Type: application/json; charset=utf-8'));
        return json_decode($javaRes,true);
    }

    /**
     * 联动优势_订单查询
     * @param $payInfo 支付信息数组
     */
    public function query($payInfo) {
        $timestamp = time();

        //准备参数
        $post_arr = [
            'mTrace' => $payInfo['res']['mTrace'],                                  //业务流水,pos批次号+流水号,这里用 我们的order_id代替
            'reqDate' => date('Ymd', $timestamp),                                   //8位日期年月日,如 20131010
            'reqTime' => date('His', $timestamp),                                   //6位时分秒,如 132018
            'posId' => $payInfo['res']['posId'],                                    //终端编号,设备号,如 DEV10552
            'pMerId' => $this->parentObj->partner_id,                               //商户号pMerId，由联动优势分配
            'orderId' => $payInfo['res']['orderId'],                                //联动优势返回的orderId
        ];

        //java签名
        $post_json = json_encode($post_arr);
        $sign = Yii::$app->kelaileJava->sign($timestamp,$post_json);
        //拼装请求路径 联动优势_云支付支付确认
        $app_id = Yii::$app->kelaileJava->appid;
        $url = Yii::$app->kelaileJava->host.self::URL_HEBAO_QUERY."?appid={$app_id}&timestamp={$timestamp}&sign={$sign}";

        //请求java接口
        $javaRes = Func::postData($url, $post_json, 10, array('Content-Type: application/json; charset=utf-8'));
        return json_decode($javaRes,true);
    }
    
}